package com.dnjn.happiness.emo.assist;

import com.dnjn.happiness.common.core.utils.JsonUtils;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.emo.config.HappinessEmoConfig;
import com.dnjn.happiness.emo.domain.UserRecordFer;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component("ferAssist")
public class FerAssist {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HappinessEmoConfig config;

    @Getter
    @Setter
    public static class FerIn implements Serializable {
        List<FerItemIn> list;
    }

    @Getter
    @Setter
    @Accessors(chain = true)
    @NoArgsConstructor
    public static class FerItemIn implements Serializable {
        private Long ferId;
        private String url;
        private Integer count;
    }

    @Getter
    @Setter

    public static class FerOut implements Serializable {
        private Integer code;
        private List<FerItem> result;
    }

    @Getter
    @Setter

    public static class FerItem implements Serializable {
        private Long ferId;

        private String emo;
        private Integer h;
        private Integer w;
        private Integer x;
        private Integer y;

        private Integer width;
        private Integer height;
        private String url;

    }


    public FerItem fetchFer(String imageUrl) {
        try {
            FerOut resp = restTemplate.getForObject(getUrl(imageUrl), FerOut.class);
            return Optional.ofNullable(resp).map(FerOut::getResult)
                    .filter(Objects::nonNull)
                    .filter(el -> el.size() > 0)
                    .map(el -> el.get(0))
                    .orElse(new FerItem());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return new FerItem();
    }


    public FerOut postFer(List<UserRecordFer> list) {

        try {
            if (Objects.isNull(list) || list.isEmpty()) {
                log.warn("invalid fer list; quit");
                return new FerOut();
            }

            FerIn in = new FerIn();
            in.setList(list.stream()
                    .map(el -> new FerItemIn().setCount(el.getFerCount()).setFerId(el.getFerId()).setUrl(el.getImageUrl()))
                    .collect(Collectors.toList()));

            log.info("req {}", JsonUtils.toJsonString(in));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> request = new HttpEntity<String>(JsonUtils.toJsonString(in), headers);

            String url = getUrl();
            FerOut resp = restTemplate.postForObject(url, request, FerOut.class);
            return resp;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return new FerOut();
    }

    private String getUrl(String imageUrl) {
        return StringUtils.format("http://{}{}?url={}", config.getDomain(), config.getFerPath(), imageUrl);
    }

    private String getUrl() {
        String url = StringUtils.format("http://{}{}", config.getDomain(), config.getFerPath());
        return url;
    }

}
